<template>
    <div id="chapter">
        <home-head></home-head>
    </div>
    <div class="header-class-main-box">
            <div class="novel-header-header">
            <!-- 导航路径 -->
<!--                分开两端-->
                <div class="breadcrumb-class-main">
                    <el-breadcrumb separator=">" class="breadcrumb-class">
                    <el-breadcrumb-item style="padding: 10px 5px" :to="{ path: '/' }">36k小说网</el-breadcrumb-item>
                            <el-breadcrumb-item
                                style="padding: 10px 0"
                                :to="{ path: categoryRouteMap[category] || '/' }">
                                {{category}}
                            </el-breadcrumb-item>
                    <el-breadcrumb-item style="padding: 10px 0;max-width: 140px" :to="{ path: `/books/list/${bookId}` }">{{ chapter.novelName}}}</el-breadcrumb-item>
                    <el-breadcrumb-item style="padding: 10px 0;max-width: 140px">{{chapter.title}}</el-breadcrumb-item>
                </el-breadcrumb>
                </div>
                <!-- 顶部工具栏 -->
                <div class="toolbar">
                <el-form inline>
                    <label class="select-label">背景颜色：</label>
                        <el-select v-model="bgColor" @change="updateStyles" size="small" class="custom-select">
                            <el-option style="background-color: #f6f6f6" value="#f6f6f6" label="默认"></el-option>
                            <el-option style="background-color: #ffffff" value="#ffffff" label="白色"></el-option>
                            <el-option style="background-color: #070707" value="#070707" label="黑色"></el-option>
                            <el-option style="background-color: #e3e8f7" value="#e3e8f7" label="淡蓝"></el-option>
                            <el-option style="background-color: #b6d9fa" value="#daebfc" label="蓝色"></el-option>
                            <el-option style="background-color: #ebeaea" value="#ebeaea" label="淡灰"></el-option>
                            <el-option style="background-color: #b2b2b2" value="#e7e3e6" label="灰色"></el-option>
                            <el-option style="background-color: #545454" value="#dedcd8" label="深灰"></el-option>
                            <el-option style="background-color: #d8d7d7" value="#d8d7d7" label="暗灰"></el-option>
                            <el-option style="background-color: #e6fae4" value="#e6fae4" label="绿色"></el-option>
                            <el-option style="background-color: #f9fbdd" value="#f9fbdd" label="明黄"></el-option>
                        </el-select>
                    <label class="select-label">文字颜色：</label>
                        <el-select v-model="textColor" @change="updateStyles" size="small" class="custom-select">
                            <el-option label="红色" value="red"></el-option>
                            <el-option label="黑色" value="black"></el-option>
                            <el-option label="绿色" value="green"></el-option>
                            <el-option label="蓝色" value="blue"></el-option>
                            <el-option label="粉色" value="pink"></el-option>
                            <el-option label="黄色" value="yellow"></el-option>
                        </el-select>
                    <label class="select-label">文字大小：</label>
                        <el-select v-model="fontSize" @change="updateStyles" size="small" class="custom-select">
                            <el-option label="小" value="small"></el-option>
                            <el-option label="中" value="medium"></el-option>
                            <el-option label="大" value="large"></el-option>
                        </el-select>
                    <label class="select-label">滚屏速度：</label>
                        <el-select v-model="scrollSpeed" @change="updateScrollSpeed" size="small" class="custom-select">
                            <el-option v-for="speed in 6" :key="speed" :label="speed" :value="speed.toString()"></el-option>
                        </el-select>
                    <el-form-item>
                        <el-switch v-model="autoScroll" @change="handleAutoScroll" active-text="自动滚屏" style="margin-left: 2px;margin-top: 20px"></el-switch>
                    </el-form-item>
                </el-form>
            </div>
            </div>
            <div class="title-card-class">
                <h1 class="center-text-class">{{ chapter.title }}</h1>
                <div class="el-button-class">
                    <el-button type="primary" size="small" @click="vote()" class="mr-2">
                        <el-icon><CirclePlus /></el-icon> 投推荐票
                    </el-button>
                    <el-button type="primary" size="small" @click="prevChapter()" class="mr-2">
                        <el-icon><ArrowLeft /></el-icon> 上一章
                    </el-button>
                    <el-button type="primary" size="small" @click="chapterList()" class="mr-2">
                        <el-icon><Menu /></el-icon> 章节列表
                    </el-button>
                    <el-button type="primary" size="small" @click="nextChapter()" class="mr-2">
                         下一章<el-icon><ArrowRight /></el-icon>
                    </el-button>
                    <el-button type="primary" size="small" @click="addBookmark()">
                        <el-icon><Star /></el-icon> 加入书架
                    </el-button>
                </div>
                <div class="recommendations">
                    <div>热门推荐</div>
                    <el-tag
                        v-for="(recommendation, index) in recommendations"
                        :key="index"
                        type="success"
                        effect="light"
                        @click="goToRecommendation(recommendation.bookId)"
                        class="mr-2  cursor-pointer"
                    >
                        {{ recommendation.title }}
                    </el-tag>
                </div>
            </div>
            <!-- 章节内容 -->
            <div class="chapter-card">
                <div class="chapter-content" :style="customStyles">
                    <div class="chapter-text">
                        <p v-for="(paragraph, index) in chapter.chapterContent" :key="index" :style="customStyles" >{{ paragraph }}</p>
                    </div>
                </div>
            </div>
            <div class="el-button-class" style="margin-top: 30px;margin-bottom: 60px">
                <el-button type="primary" size="small" @click="vote()" class="mr-2">
                    <el-icon><CirclePlus /></el-icon> 投推荐票
                </el-button>
                <el-button type="primary" size="small" @click="prevChapter()" class="mr-2">
                    <el-icon><ArrowLeft /></el-icon> 上一章
                </el-button>
                <el-button type="primary" size="small" @click="chapterList()" class="mr-2">
                    <el-icon><Menu /></el-icon> 章节列表
                </el-button>
                <el-button type="primary" size="small" @click="nextChapter()" class="mr-2">
                     下一章<el-icon><ArrowRight /></el-icon>
                </el-button>
                <el-button type="primary" size="small" @click="addBookmark()">
                    <el-icon><Star /></el-icon> 加入书架
                </el-button>
            </div>
    </div>
    <HomeBottom />
</template>

<script setup>
import HomeHead from "@/components/home/home-head.vue";
import { ref, onMounted, computed ,onUnmounted} from 'vue'
import {
    CirclePlus, ArrowLeft, ArrowRight, Menu, Star,
} from '@element-plus/icons-vue'
import HomeBottom from "@/components/home/home-bottom.vue";
import {ElLoading, ElMessage} from 'element-plus'
import request from '@/utils/request.js';
import router from "@/router/index.js";

const isLoading = ref(true);
const data =defineProps({
    bookId: String, // 或Number
    id: String
});
const categoryRouteMap = {
    '玄幻小说': '/XuanHuan',
    '网游小说': '/WangYou',
    '武侠小说': '/WuXia',
    '都市小说': '/DouShi',
    '科幻小说': '/KeHuang',
    '历史小说': '/LiShi',
    '言情小说': '/YanQin'

};
// 章节数据
const chapter = ref({
    title: "",
    chapterContent: [],
    id: data.id,
    bookId: data.bookId,
    novelName: ""
})
// 样式设置
const bgColor = ref("默认")
const textColor = ref("black")
const fontSize = ref("medium")
const scrollSpeed = ref("3")
const autoScroll = ref(false)
const textColorMap = {
    red: '#ff0000',
    black: '#000000',
    green: '#008000',
    blue: '#0000ff',
    pick: '#ffd6d6',
    yellow: '#ffff00'
}
// 计算样式
const customStyles = computed(() => {
    const styles = {
        color: textColor.value === '默认' ? '#333' :
            textColorMap[textColor.value] || textColor.value,
        lineHeight: '1.8',
        transition: 'all 0.3s ease'
    }
    // 背景颜色处理
    if (bgColor.value !== "默认") {
        styles.backgroundColor = bgColor.value
    }
    // 字体大小处理
    switch(fontSize.value) {
        case "small":
            styles.fontSize = "15px"
            break
        case "medium":
            styles.fontSize = "22px"
            break
        case "large":
            styles.fontSize = "30px"
            break
        default:
            styles.fontSize = "18px" // 默认值，防止未定义情况
    }
    return styles
})



// 清理自动滚屏定时器
// 更新样式
const updateStyles = () => {
    // 样式通过computed自动更新
    ElMessage.success('样式已更新')
}

let scrollInterval;
// 开始自动滚屏（核心修改）
const startAutoScroll = () => {
    scrollInterval = setInterval(() => {
        // 页面当前滚动位置（顶部距离）
        const currentScrollTop = window.scrollY;
        // 浏览器可视区域高度
        const clientHeight = window.innerHeight;
        // 整个页面的内容总高度（包括不可见部分）
        const scrollHeight = document.body.scrollHeight || document.documentElement.scrollHeight;
        // 计算每次滚动的距离（基于速度）
        const step = parseInt(scrollSpeed.value);
        // 滚动页面（向下滚动 step 像素）
        window.scrollBy(0, step);
        // 判断是否到达底部（当前滚动位置 + 可视高度 >= 内容总高度 - 缓冲值）
        // 增加20px缓冲，避免浏览器计算误差
        const isBottom = currentScrollTop + clientHeight >= scrollHeight - 20;
        if (isBottom) {
            autoScroll.value = false;
            clearInterval(scrollInterval);
            ElMessage.info('已到达章节末尾');
        }
    }, 50); // 每50ms滚动一次
};
// 停止自动滚屏（保持）
const handleAutoScroll = () => {
    if (autoScroll.value) {
        startAutoScroll();
        ElMessage.info(`已开启自动滚屏，速度：${scrollSpeed.value}`);
    } else {
        clearInterval(scrollInterval);
        scrollInterval=null
        ElMessage.info('已关闭自动滚屏');
    }
};
// 更新滚屏速度（保持，无需修改）
const updateScrollSpeed = () => {
    if (autoScroll.value) {
        clearInterval(scrollInterval);
        startAutoScroll();
    }
};
// 键盘事件处理函数
const handleKeydown = (e) => {
    // 只处理左右方向键，避免影响其他输入（如搜索框输入）
    if (e.key === 'ArrowLeft') {
        // 左键：上一章
        prevChapter();
        e.preventDefault(); // 阻止默认行为（如页面左滚）
    } else if (e.key === 'ArrowRight') {
        // 右键：下一章
        nextChapter();
        e.preventDefault(); // 阻止默认行为（如页面右滚）
    }
};
const category=ref("")
request.get('/api/books/categories' ,{
    params: {
        bookId: chapter.value.bookId  // 正确传递GET参数（键为后端要求的参数名，如bookId）
    }
}).then(
            res => {
                if (res.code === 200) {
                     category.value = res.data;
                }
            }
        ).catch( error=> {
            ElMessage.error('获取小说列表失败：' + (res.message || '数据格式错误'));
        })
// 初始化
onMounted(() => {
    // 从API加载章节数据
    fetchChapterData(chapter.value.bookId, chapter.value.id)
    // 添加键盘事件监听（全局）
    window.addEventListener('keydown', handleKeydown);
})
// 数据接口调用 - 加载章节数据
const fetchChapterData =  (bookId, chapterId) => {
    // 使用 ElLoading.service 创建加载状态
    const loading = ElLoading.service({
        lock: true,
        text: '加载中...',
        background: 'rgba(0, 0, 0, 0.7)'
    });
    request.get(`/api/books/${bookId}/chapters/${chapterId}`).then( response=>{
        if (response.code === 200 && response.data) {
            const data = response.data;
            // 将 chapterContent 字符串按换行符分割成数组
            data.chapterContent = data.chapterContent.split('\n');
            chapter.value = data;
        }
    }).catch(error => {
        ElMessage.error('网络错误：' + error.message);
    }).finally(() => {
        // 关闭加载状态
        loading.close();
    });
};

// 上一章（ID-1逻辑）
const prevChapter =async  () => {
    // 1. 验证当前章节ID有效性
    if (!chapter.value.id) {
        ElMessage.error('章节信息异常');
        return;
    }
    // 2. 转换ID为数字并计算上一章ID
    const currentId = Number(chapter.value.id);
    if (isNaN(currentId)) {
        ElMessage.error('章节ID格式错误');
        return;
    }
    const prevId = currentId - 1;
    // 3. 边界判断（防止ID为负数）
    if (prevId < 1) {
        ElMessage.info('已经是第一章了');
        return;
    }
    // 4. 加载上一章数据
    try {
        const loading = ElLoading.service({ text: '加载上一章...' });
        const response =  await  request.get(`/api/books/${chapter.value.bookId}/chapters/${prevId}`);
        if (response.code === 200 && response.data) {
            // 处理章节内容为数组
            response.data.chapterContent = response.data.chapterContent.split('\n');
            chapter.value = response.data;
            scrollToTop();
            router.push({
                path: `/chapter/${chapter.value.bookId}/${prevId}`, // 根据实际路由路径修改
                replace: false // 保留历史记录，允许后退
            });
        } else {
            ElMessage.error('未找到上一章内容');
        }
        loading.close();
    } catch (error) {
        console.error('上一章加载失败:', error);
        ElMessage.error('网络错误，无法加载上一章');
        loading.close();
    }
};

// 下一章（ID+1逻辑）
const nextChapter = async () => {
    // 1. 验证当前章节ID有效性
    if (!chapter.value.id) {
        ElMessage.error('章节信息异常');
        return;
    }
    // 2. 转换ID为数字并计算下一章ID
    const currentId = Number(chapter.value.id);
    if (isNaN(currentId)) {
        ElMessage.error('章节ID格式错误');
        return;
    }
    const nextId = currentId + 1;
    // 3. 加载下一章数据
    try {
        const loading = ElLoading.service({ text: '加载下一章...' });
        const response =  await  request.get(`/api/books/${chapter.value.bookId}/chapters/${nextId}`);

        if (response.code === 200 && response.data) {
            // 处理章节内容为数组
            response.data.chapterContent = response.data.chapterContent.split('\n');
            chapter.value = response.data;
            // await nextTick();
            scrollToTop();
            router.push({
                path: `/chapter/${chapter.value.bookId}/${nextId}`, // 根据实际路由路径修改
                replace: false // 保留历史记录，允许后退
            });
            ElMessage.success(`已切换到第${nextId}章`);
        } else {
            ElMessage.info('已经是最后一章了');
        }
        loading.close();
    } catch (error) {
        console.error('下一章加载失败:', error);
        ElMessage.error('网络错误，无法加载下一章');
        loading.close();
    }
};
// 章节列表
const chapterList = () => {
    router.push(`/books/list/${chapter.value.bookId}`)
}
// 投推荐票//需要登录
const vote =  () => {
    try {
        const response =  request.post(`/api/user/books/${bookId}/vote`)
        if (response.code===200) {
            ElMessage.success('推荐票已投出，感谢支持！')
        }
    } catch (error) {
        console.error('投票失败:', error)
        ElMessage.error('投票失败，请重试')
    }
}
// 加入书架//需要登录
const addBookmark =  () => {
    try {
        const  response =  request.post(`/api/users/bookmarks`, {
            bookId: chapter.value.bookId,
            chapterId: chapter.value.id,
            IsBookshelf:0,//判断是不是书架
            position: window.scrollY || 0, // 记录页面当前滚动位置
        }).then(response=>{
                if (response.code===200) {
                    ElMessage.success('已成功加入书架')
                }else {
                    ElMessage.error('添加书架失败: ' + response.message)
                }
            }
        )
    } catch (error) {
        console.error('加入书架失败:', error)
        ElMessage.error('添加书架失败，请重试')
    }
}
//加入书签
const addBookm =  () => {
    try {
        const response = request.post(`/api/users/bookmarks`, {
            bookId: chapter.value.bookId,
            chapterId: chapter.value.id,
            IsBookshelf: 1,//判断是不是书架
            position: window.scrollY || 0, // 记录页面当前滚动位置
        }).then(response => {
                if (response.code === 200) {
                    ElMessage.success('已经成功记录书签')
                } else {
                    ElMessage.error('添加书签失败: ' + response.message)
                }
            }
        )
    } catch (error) {
        console.error('加入书签失败:', error)
        ElMessage.error('加入书签失败，请重试')
    }
}

// 推荐小说
const recommendations = ref([
        { title: "诸天影视从四合院开始", bookId: 1 },
        { title: "从小欢喜开启诸天之旅", bookId: 2 },
        { title: "火影：我在暗部苟成超影", bookId: 3 },
        { title: "狗尾续貂传", bookId: 4 },
        { title: "进化乐园，您就是天灾？", bookId: 826017 }
    ]
)
// 跳转到推荐小说
const goToRecommendation = (id) => {
    router.push(`/books/list/${id}`)
}
// 跳转到指定页面
const goToChapter = (type) => {
    ElMessage.info(`跳转到：${type}`)
    // 实际项目中实现跳转逻辑
    /*
    switch(type) {
      case 'index':
        router.push('/')
        break
      case 'category':
        router.push('/categories/online-game')
        break
      case 'book':
        router.push(`/books/${chapter.value.bookId}`)
        break
    }
    */
}
// 滚动到顶部（优化版）
const scrollToTop = () => {
    // 先尝试平滑滚动，失败则强制滚动到顶部
    window.scrollTo({ top: 0, behavior: 'smooth' });
    // 强制兜底（防止平滑滚动失效）
    setTimeout(() => {
        window.scrollTo(0, 0);
    }, 100);
};
onUnmounted(() => {
    // 页面正常跳转时主动保存一次
    addBookm();
    window.removeEventListener('keydown', handleKeydown);
    // 清除自动滚屏定时器（完善清理逻辑）
    if (scrollInterval) {
        clearInterval(scrollInterval);
        scrollInterval = null;
    }
});
</script>
<style scoped>
.header-class-main-box {
    margin: 20px auto; /* 居中显示 */
    width: 1200px;
    border: 3px solid #6bb2fc; /* 蓝色边框 */
    /*padding: 5px; !* 内边距 *!*/
    border-radius: 4px; /* 可选：圆角边框 */
    background-color: #f6f6f6;
}
.novel-header-header{
    display: flex;
    justify-content: space-between; /* 关键：强制两端对齐 */
    align-items: center; /* 垂直居中对齐 */
    margin-bottom: 20px;
    width: 1200px;
    height: 50px; /* 固定高度 */
    background-color: #eefcfc;
}
.breadcrumb-class-main{
    display: flex;
    align-items: center;
    height: 50px;
}
.el-breadcrumb {
    margin-bottom: 10px;
    height: 100%; /* 关键：使用100%高度继承父容器 */
    display: flex;
    align-items: center; /* 垂直居中内容 */
    font-size: 0.8rem;
}

.toolbar{
    margin-left: 20px;
    height: 50px;
    font-size: 1rem;
    display: flex;
    align-items: center; /* 垂直居中内容 */
}

.custom-select{
    width: 60px;
}
.title-card-class{
    /*margin: 20px 60px;*/
    /*background-color: #409eff;*/
}
.center-text-class{
    text-align: center;
    font-size: 3rem;
}
.el-button-class{
    margin-top: 30px;
    /*margin-left: 20px;*/
    text-align: center;
}
.mr-2{
    margin-right: 20px;
    font-size: 1rem;
}
.chapter-card {

}

.chapter-content {
    padding: 40px;
    transition: all 0.3s ease;
}


.chapter-text {
    text-align: justify;
}

.recommendations {
    display: flex;
    margin-top: 30px;
    max-width: 1200px;
/*    不允许换行*/
    white-space: nowrap;
margin-bottom: 40px;
}

.cursor-pointer {
    cursor: pointer;
}


.chapter-content {
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;


}
.chapter-content p {
    margin-bottom: 1.5em;
    text-indent: 2em;
    text-align: justify;
}

</style>